local extension = Package("ling10")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["lingling__hunyi"] = "混一",
  [":lingling__hunyi"] = "出牌阶段限一次，你可以获得所有其他角色所有手牌，然后其他角色依次获得你X张手牌（X为其此次失去的手牌数），你可以"..
  "令一名其他角色优先获得。",
  ["lingling__zeshan"] = "择善",
  [":lingling__zeshan"] = "每回合限一次，当你与其距离为1或其与你距离为1的其他角色获得你的牌时，你可以防止之，然后交给其等量牌。"..
  "<br><br> <font color = '#a40000'>遂辟雄图，混一中外；德威所指，无远弗届。",
}

local bayan = General(extension, "lingling__bayan", "yuan", 4)
local qinfeng = fk.CreateTriggerSkill{
  name = "lingling__qinfeng",
  anim_type = "control",
  events = {fk.CardUseFinished, fk.CardRespondFinished, fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if table.contains({fk.CardUseFinished, fk.CardRespondFinished}, event) then
        return target == player
      elseif event == fk.TurnEnd then
        return table.find(player.room.alive_players, function (p)
          return player:distanceTo(p) == 1 and not p:isNude()
        end)
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if table.contains({fk.CardUseFinished, fk.CardRespondFinished}, event) then
      self.cost_data = nil
      return true
    elseif event == fk.TurnEnd then
      local room = player.room
      local targets = table.filter(room.alive_players, function (p)
        return player:distanceTo(p) == 1 and not p:isNude()
      end)
      local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 2,
        "#lingling__qinfeng-choose", self.name, true)
      if #tos > 0 then
        room:sortPlayersByAction(tos)
        self.cost_data = {tos = tos}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished or event == fk.CardRespondFinished then
      room:addPlayerMark(player, "@lingling__qinfeng-turn", 1)
    elseif event == fk.TurnEnd then
      for _, id in ipairs(self.cost_data.tos) do
        if player.dead then return end
        local p = room:getPlayerById(id)
        if not p.dead and not p:isNude() then
          local card = room:askForCardChosen(player, p, "he", self.name, "#lingling__qinfeng-prey::"..p.id)
          room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
          if player.dead or not table.contains(player:getCardIds("h"), card) then return end
          card = Fk:getCardById(card)
          if card.type == Card.TypeEquip and player:canUseTo(card, player) and
            room:askForSkillInvoke(player, self.name, nil, "#lingling__qinfeng-use:::"..card:toLogString()) then
            room:useCard{
              from = player.id,
              tos = {{player.id}},
              card = card,
            }
          end
        end
      end
    end
  end,
}
local qinfeng_distance = fk.CreateDistanceSkill{
  name = "#lingling__qinfeng_distance",
  correct_func = function(self, from, to)
    if from:hasSkill(qinfeng) then
      return 2 - from:getMark("@lingling__qinfeng-turn")
    end
  end,
}
local feidu = fk.CreateViewAsSkill{
  name = "lingling__feidu",
  anim_type = "offensive",
  prompt = "#lingling__feidu",
  card_filter = function(self, player, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "jink"
  end,
  view_as = function(self, player, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("duel")
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
}
local feidu_prohibit = fk.CreateProhibitSkill{
  name = "#lingling__feidu_prohibit",
  is_prohibited = function(self, from, to, card)
    return table.contains(card.skillNames, "lingling__feidu") and from:distanceTo(to) < 2
  end,
}
qinfeng:addRelatedSkill(qinfeng_distance)
feidu:addRelatedSkill(feidu_prohibit)
bayan:addSkill(qinfeng)
bayan:addSkill(feidu)
Fk:loadTranslationTable{
  ["lingling__bayan"] = "伯颜",
  ["#lingling__bayan"] = "天诛之公",
  ["illustrator:lingling__bayan"] = "珊瑚虫",
  ["designer:lingling__bayan"] = "伶",

  ["lingling__qinfeng"] = "擒风",
  [":lingling__qinfeng"] = "你计算与其他角色的距离+2。当你使用或打出一张牌后，本回合你计算与其他角色的距离-1。任意回合结束时，"..
  "你可以获得至多两名你与其距离为1的其他角色各一张牌，若为装备牌你可以使用。",
  ["lingling__feidu"] = "飞渡",
  [":lingling__feidu"] = "出牌阶段，你可以将【闪】当【决斗】对一名你与其距离大于1的其他角色使用。"..
  "<br><br> <font color = '#a40000'>统二十万大军伐宋，如统一人，诸帅仰之若神明。",
  ["@lingling__qinfeng-turn"] = "擒风",
  ["#lingling__qinfeng-choose"] = "擒风：你可以获得至多两名距离为1的角色各一张牌",
  ["#lingling__qinfeng-prey"] = "擒风：获得 %dest 一张牌，若为装备牌可以使用之",
  ["#lingling__qinfeng-use"] = "擒风：是否使用%arg？",
  ["#lingling__feidu"] = "飞渡：你可以将【闪】当【决斗】对距离大于1的角色使用",
}

local yelvchucai = General(extension, "lingling__yelvchucai", "yuan", 3)
local zhongliu = fk.CreateActiveSkill{
  name = "lingling__zhongliu",
  anim_type = "drawcard",
  card_num = 0,
  target_num = 0,
  prompt = "#lingling__zhongliu",
  card_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local cards = room:getNCards(7)
    room:moveCardTo(cards, Card.Processing, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
    local targets = table.filter(room:getOtherPlayers(player), function (p)
      return #room.logic:getActualDamageEvents(1, function(e)
        local damage = e.data[1]
        return damage.to == player and damage.from == p
      end, Player.HistoryGame) > 0
    end)
    if #targets > 0 then
      local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#lingling__zhongliu-choose", self.name, false)
      to = room:getPlayerById(to[1])
      local n = math.min(#cards, 2)
      local ids = U.askforChooseCardsAndChoice(to, cards, {"OK"}, self.name, "#lingling__zhongliu-discard:::"..n, nil, n, 2)
      for _, id in ipairs(ids) do
        table.removeOne(cards, id)
      end
      room:moveCardTo(ids, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, nil, true, to.id)
      if #cards == 0 then return end
    end
    if player.dead then
      room:cleanProcessingArea(cards)
      return
    end
    targets = table.filter(room:getOtherPlayers(player), function (p)
      return #room.logic:getActualDamageEvents(1, function(e)
        local damage = e.data[1]
        return damage.to == player and damage.from == p
      end, Player.HistoryGame) == 0
    end)
    if #targets > 0 then
      local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#lingling__zhongliu-choose", self.name, false)
      to = room:getPlayerById(to[1])
      local n = math.min(#cards, 2)
      local ids = U.askforChooseCardsAndChoice(to, cards, {"OK"}, self.name, "#lingling__zhongliu-discard:::"..n, nil, n, 2)
      for _, id in ipairs(ids) do
        table.removeOne(cards, id)
      end
      room:moveCardTo(ids, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, nil, true, to.id)
      if #cards == 0 then return end
    end
    if player.dead then
      room:cleanProcessingArea(cards)
      return
    end
    if #cards > 3 then
      local ids = U.askforChooseCardsAndChoice(player, cards, {"OK"}, self.name, "#lingling__zhongliu-prey", nil, 3, 3)
      for _, id in ipairs(ids) do
        table.removeOne(cards, id)
      end
      room:moveCardTo(ids, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
      room:cleanProcessingArea(cards)
    else
      room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
  end,
}
local salei = fk.CreateTriggerSkill{
  name = "lingling__salei",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.EnterDying, fk.Death},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EnterDying then
      return player:hasSkill(self) and player:distanceTo(target) == 1 and not player:isNude()
    elseif event == fk.Death then
      return target == player and player:hasSkill(self, false, true) and
        data.damage and data.damage.from and not data.damage.from:isNude()
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.EnterDying then
      room:notifySkillInvoked(player, self.name, "negative")
      room:askForDiscard(player, 2, 2, true, self.name, false)
    elseif event == fk.Death then
      room:notifySkillInvoked(player, self.name, "control")
      data.damage.from:throwAllCards("he")
    end
  end,
}
yelvchucai:addSkill(zhongliu)
yelvchucai:addSkill(salei)
Fk:loadTranslationTable{
  ["lingling__yelvchucai"] = "耶律楚材",
  ["#lingling__yelvchucai"] = "玉泉老人",
  ["illustrator:lingling__yelvchucai"] = "VT",
  ["designer:lingling__yelvchucai"] = "伶",

  ["lingling__zhongliu"] = "中流",
  [":lingling__zhongliu"] = "出牌阶段限一次，你可以亮出牌堆顶七张牌，令一名对你造成过伤害的其他角色弃置其中两张牌，再令一名未对你造成过伤害的"..
  "其他角色弃置其中两张牌，没有符合条件的其他角色则跳过，然后你从剩余牌中获得三张牌。",
  ["lingling__salei"] = "洒泪",
  [":lingling__salei"] = "你与其距离为1的其他角色进入濒死状态后，你弃置两张牌。你死亡后，杀死你的角色弃置所有牌。"..
  "<br><br> <font color = '#a40000'>虽楚有材，晋实用之。",
  ["#lingling__zhongliu"] = "中流：亮出牌堆顶七张牌，获得其中的牌",
  ["#lingling__zhongliu-choose"] = "中流：令一名角色弃置其中两张牌",
  ["#lingling__zhongliu-discard"] = "中流：请弃置其中%arg张牌",
  ["#lingling__zhongliu-prey"] = "中流：获得其中三张牌",
}

Fk:loadTranslationTable{
  ["lingling__guanhanqing"] = "关汉卿",
  ["#lingling__guanhanqing"] = "高才风流",
  ["illustrator:lingling__guanhanqing"] = "珊瑚虫",
  ["designer:lingling__guanhanqing"] = "伶",

  ["lingling__jiqu"] = "激曲",
  [":lingling__jiqu"] = "出牌阶段限一次，你可以发动〖焚城〗，然后你选择：本回合80%几率改为预演回合；失去此技能。",
  ["lingling__yiliu"] = "一流",
  [":lingling__yiliu"] = "转换技，当一名你与其距离为1以内的角色受到伤害后，你可以将手牌调整至①1张②X张（X为本轮你手牌最多时的手牌数+1）。"..
  "<br><br> <font color = '#a40000'>关汉卿之词，如琼筵醉客。<br>观其词语，乃可上可下之才。",
}

Fk:loadTranslationTable{
  ["lingling__ahmad_fanākatī"] = "阿合马",
  ["#lingling__ahmad_fanākatī"] = "益肆贪横",
  ["illustrator:lingling__ahmad_fanākatī"] = "珊瑚虫",
  ["designer:lingling__ahmad_fanākatī"] = "伶",

  ["lingling__zhuanying"] = "专营",
  [":lingling__zhuanying"] = "出牌阶段限一次，你可以将装备牌当额外摸一张牌的【无中生有】使用。以此法获得的牌不计入手牌上限，且你造成伤害后弃置之。",
  ["lingling__zhuanheng"] = "专横",
  [":lingling__zhuanheng"] = "当你与其距离为1的其他角色失去装备牌时，你可以重铸一张牌，令其选择：交给你这些装备牌；视为你对其使用无次数限制的"..
  "【杀】。"..
  "<br><br> <font color = '#a40000'>交钞可以权万货者，法使然也。",
}

local lichahan = General(extension, "lingling__chaqan_temür", "yuan", 4)
local pohong = fk.CreateTriggerSkill{
  name = "lingling__pohong",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash" and
      #player:getCardIds("he") >= player:distanceTo(player.room:getPlayerById(data.to))
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local n = player:distanceTo(room:getPlayerById(data.to))
    local cards = room:askForDiscard(player, n, n, true, self.name, true, nil, "#lingling__pohong-invoke::"..data.to..":"..n, true)
    if #cards == n then
      self.cost_data = {tos = {data.to}, cards = cards}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(data.to)
    room:throwCard(self.cost_data.cards, self.name, player, player)
    local cards = table.simpleClone(to:getCardIds("h"))
    table.insertTable(cards, room:getNCards(3))
    cards = table.filter(cards, function (id)
      return Fk:getCardById(id).color == Card.Red
    end)
    if #cards == 0 then return end
    cards = table.random(cards, 3)
    local moves = {}
    local ids = table.filter(cards, function (id)
      return table.contains(to:getCardIds("h"), id)
    end)
    if #ids > 0 then
      table.insert(moves, {
        ids = ids,
        from = data.to,
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonDiscard,
        skillName = self.name,
        proposer = player.id,
        moveVisible = true,
      })
    end
    ids = table.filter(cards, function (id)
      return table.contains(room.draw_pile, id)
    end)
    if #ids > 0 then
      table.insert(moves, {
        ids = ids,
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonDiscard,
        skillName = self.name,
        proposer = player.id,
        moveVisible = true,
      })
    end
    room:moveCards(table.unpack(moves))
  end,
}
local huigong = fk.CreateViewAsSkill{
  name = "lingling__huigong",
  anim_type = "offensive",
  pattern = "slash",
  prompt = "#lingling__huigong",
  card_filter = function(self, player, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "jink"
  end,
  view_as = function(self, player, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("slash")
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
  before_use = function (self, player, use)
    player.room:setPlayerMark(player, "lingling__huigong-turn", 1)
    use.extraUse = true
  end,
  enabled_at_play = function (self, player)
    return player:getMark("lingling__huigong-turn") == 0
  end,
  enabled_at_response = function (self, player, response)
    return not response and player:getMark("lingling__huigong-turn") == 0
  end,
}
local huigong_targetmod = fk.CreateTargetModSkill{
  name = "#lingling__huigong_targetmod",
  bypass_times =  function(self, player, skill, scope, card, to)
    return card and table.contains(card.skillNames, "lingling__huigong")
  end,
}
local huigong_delay = fk.CreateTriggerSkill{
  name = "#lingling__huigong_delay",
  anim_type = "drawcard",
  main_skill = huigong,
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(huigong) and
      table.find(player.room:getBanner("@$CenterArea"), function (id)
        local card = Fk:getCardById(id)
        return card.color == Card.Red and not table.contains(player:getTableMark("lingling__huigong_record-turn"), card.trueName)
      end)
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local all_cards = table.filter(room:getBanner("@$CenterArea"), function (id)
      local card = Fk:getCardById(id)
      return card.color == Card.Red and not table.contains(player:getTableMark("lingling__huigong_record-turn"), card.trueName)
    end)
    local cards = U.askforChooseCardsAndChoice(player, all_cards, {"OK"}, "lingling__huigong",
      "#lingling__huigong-prey", {"Cancel"}, 1, 2, player.room:getBanner("@$CenterArea"))
    if #cards > 0 then
      self.cost_data = {cards = cards}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(self.cost_data.cards) do
      room:addTableMark(player, "lingling__huigong_record", Fk:getCardById(id).trueName)
    end
    room:moveCardTo(self.cost_data.cards, Card.PlayerHand, player, fk.ReasonJustMove, "lingling__huigong", nil, true, player.id)
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("lingling__huigong_record") ~= 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "lingling__huigong_record-turn", player:getMark("lingling__huigong_record"))
    room:setPlayerMark(player, "lingling__huigong_record", 0)
  end,
}
huigong:addRelatedSkill(huigong_targetmod)
huigong:addRelatedSkill(huigong_delay)
lichahan:addSkill(pohong)
lichahan:addSkill(huigong)
Fk:loadTranslationTable{
  ["lingling__chaqan_temür"] = "李察罕",
  ["#lingling__chaqan_temür"] = "白铁大将",
  ["illustrator:lingling__chaqan_temür"] = "珊瑚虫",
  ["designer:lingling__chaqan_temür"] = "伶",

  ["lingling__pohong"] = "破红",
  [":lingling__pohong"] = "当你使用【杀】指定其他角色为目标后，你可以弃置X张牌（X为你与其的距离），然后从其手牌和牌堆顶三张牌中随机弃置"..
  "共计三张红色牌。",
  ["lingling__huigong"] = "回攻",
  [":lingling__huigong"] = "每回合限一次，你可以将【闪】当无次数限制的【杀】使用。回合结束时，你可以获得中央区至多两张红色牌，不能与上回合"..
  "以此法获得的牌名相同。"..
  "<br><br> <font color = '#a40000'>草之劲者非疾风不显，人之忠者非乱世难名。",
  ["#lingling__pohong-invoke"] = "破红：是否弃置%arg张牌，弃置 %dest 手牌和牌堆顶三张牌中随机三张红色牌？",
  ["#lingling__huigong"] = "回攻：你可以将【闪】当无次数限制的【杀】使用",
  ["#lingling__huigong_delay"] = "回攻",
  ["#lingling__huigong-prey"] = "回攻：你可以获得其中至多两张红色牌",
}

return extension
